<?php
/**
 * Created by PhpStorm.
 * User: hedx
 * Date: 2016/3/30
 * Time: 18:51
 */

namespace common\mq\utils;

use common\mq\models\MessageAttributes;
use common\mq\models\MessageConstants;
use common\mq\models\MessageServiceModel;
use common\mq\models\MessageServiceSendModel;
use common\utils\DateTimeUtil;
use common\utils\DateTimeUtils;
use common\utils\DomainUtil;
use Yii;
use yii\base\Exception;

class MessageUtils
{
    /**
     * 把消息总表的一条记录解析成消息发送表的一条记录
     *
     * @param MessageServiceModel $messageService
     * @return MessageServiceSendModel
     * @throws Exception 解析错误时抛出异常
     */
    public static function resolveMessage($messageService)
    {
        if (empty($messageService->id) || empty($messageService->queue_name) || empty($messageService->message_content)) {
            throw new Exception("Message resolve failed! Please specify message 'id', 'queueName' and 'content' for resolve message!");
        }
        $messageSend = new MessageServiceSendModel();
        $messageSend->message_service_id = $messageService->id;
        $messageSend->queue_name = $messageService->queue_name;
        $messageSend->message_type = $messageService->message_type;
        $messageSend->message_priority = $messageService->message_priority;
        $messageSend->message_delay_seconds = $messageService->message_delay_seconds;
        $messageSend->message_body = self::getMessageBody($messageService, $messageService->queue_name);
        return $messageSend;
    }

    /**
     * 根据MessageServiceModel内容封装一个messageBody的消息主体
     * 格式: json => {"title":"foo1","batch":"foo2","type":"foo3","sender":"foo4","receiver":"foo5","content":"foo6"}
     * @param MessageServiceModel $message
     * @return object json格式的messageBody
     */
    public static function getMessageBody($message, $queueName)
    {
        $messageBody = [
            "serviceId" => $message->id,
            "queue" => $queueName,
            "batch" => $message->message_batch,
            "type" => $message->message_type,
            "title" => $message->message_title,
            "sender" => $message->message_sender,
            "receiver" => $message->message_receiver,
            "content" => $message->message_content
        ];
        return json_encode($messageBody, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 装一个messageBody的消息主体
     * 格式: json => {"title":"foo1","batch":"foo2","type":"foo3","sender":"foo4","receiver":"foo5","content":"foo6"}
     * @param MessageAttributes $message
     * @return object json格式的messageBody
     */
    public static function getMessageBodyByAttributes(MessageAttributes $message, $queueName)
    {
        $messageBody = [
            "serviceId" => '', //废弃
            "queue" => $queueName,
            "batch" => $message->getBatch(),
            "type" => $message->getType(),
            "title" => $message->getTitle(),
            "sender" => $message->getSender(),
            "receiver" => $message->getReceiver(),
            "content" => $message->getContent()
        ];
        return json_encode($messageBody, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 解析消息体，返回一个对象包含serviceId,batch,title,sender,receiver和content属性
     *
     * @param $messageBody
     * @return object
     */
    public static function resolveMessageBody($messageBody)
    {
        $decodeMessageBody = json_decode($messageBody);
        if (is_object($decodeMessageBody)) {
            if (!property_exists($decodeMessageBody, "serviceId")) {
                $decodeMessageBody->serviceId = "";
            }
            if (!property_exists($decodeMessageBody, "queue")) {
                $decodeMessageBody->queue = "";
            }
            if (!property_exists($decodeMessageBody, "batch")) {
                $decodeMessageBody->batch = "";
            }
            if (!property_exists($decodeMessageBody, "type")) {
                $decodeMessageBody->type = "";
            }
            if (!property_exists($decodeMessageBody, "title")) {
                $decodeMessageBody->title = "";
            }
            if (!property_exists($decodeMessageBody, "sender")) {
                $decodeMessageBody->sender = "";
            }
            if (!property_exists($decodeMessageBody, "receiver")) {
                $decodeMessageBody->receiver = "";
            }
            if (!property_exists($decodeMessageBody, "content")) {
                $decodeMessageBody->content = "";
            }
        } else {
            $decodeMessageBody = json_decode(json_encode(["serviceId" => "", "queue" => "", "batch" => "",
                "title" => "", "sender" => "", "receiver" => "", "content" => ""]));
        }
        return $decodeMessageBody;
    }

    /**
     * 获取相关队列的优先级
     *
     * @param string $queueName
     * @return int priority 返回该队列的优先级
     */
    public static function getPriority($queueName)
    {
        $priority = 8; // 默认值
        switch ($queueName) {
            case MessageConstants::QUEUE_NAME_TEST :
                $priority = 16;
                break;
            case MessageConstants::QUEUE_NAME_VERIFY_CODE:
            case MessageConstants::QUEUE_NAME_VOICE_VERIFY_CODE:
                $priority = 1;
                break;
            case MessageConstants::QUEUE_NAME_SMS :
                $priority = 3;
                break;
            case MessageConstants::QUEUE_NAME_EMAIL :
                $priority = 6;
                break;
        }
        return $priority;
    }

    /**
     * 消息监控系统中:把result结果集填充到monitor map中
     *
     * @param $results
     * @return array
     */
    public static function fillMonitorMap($results)
    {
        $monitorMap = [];
        if (!empty($results)) {
            foreach ($results as $record) {
                if (is_array($record) && sizeof($record) == 2) {
                    $monitorMap[$record["messagePhase"]] = intval($record["messageCount"]);
                }
            }
        }
        if (!array_key_exists(MessageServiceModel::PHASE_CREATED, $monitorMap)) {
            $monitorMap[MessageServiceModel::PHASE_CREATED] = 0;
        }
        if (!array_key_exists(MessageServiceModel::PHASE_SENT, $monitorMap)) {
            $monitorMap[MessageServiceModel::PHASE_SENT] = 0;
        }
        if (!array_key_exists(MessageServiceModel::PHASE_RECEIVED, $monitorMap)) {
            $monitorMap[MessageServiceModel::PHASE_RECEIVED] = 0;
        }

        return $monitorMap;
    }

}